<template>
  <div
    style="max-width: 900px; margin: 20px auto; padding: 0 15px"
    class="distributor"
  >
    <!-- 分销员认证状态信息 -->
    <el-card style="margin-bottom: 20px">
      <div class="title">当前分销员认证状态</div>
      <div style="padding: 10px 20px">
        <el-alert
          :title="statusTitle"
          :type="statusType"
          :closable="false"
          show-icon
          :description="statusText"
        >
          <template #icon>
            <el-icon name="user-solid" v-if="authStatus === '1'" />
            <el-icon name="loading" v-else-if="authStatus === '0'" />
            <el-icon name="circle-close" v-else-if="authStatus === '2'" />
            <el-icon name="edit" v-else />
          </template>
        </el-alert>
      </div>
    </el-card>

    <!-- 上级绑定按钮，只有已成为分销员且无上级的用户才显示 -->
    <el-button
      v-if="
        authStatus === '1' &&
        (!distributorInfo.fatherId || distributorInfo.fatherId === 0)
      "
      type="primary"
      @click="showBindSuperiorDialog"
      size="small"
    >
      上级绑定
    </el-button>

    <!-- 分销员信息填写 -->
    <el-card
      style="margin-bottom: 20px"
      v-if="authStatus === null || authStatus === '2'"
    >
      <div class="title">分销员认证申请</div>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        label-position="right"
      >
        <el-form-item label="真实姓名" prop="realName">
          <el-input
            v-model="form.realName"
            placeholder="请输入真实姓名"
            clearable
          />
        </el-form-item>

        <el-form-item label="手机号码" prop="mobile">
          <el-input
            v-model="form.mobile"
            placeholder="请输入手机号"
            maxlength="11"
          />
        </el-form-item>

        <el-form-item label="身份证号" prop="identityCard">
          <el-input
            v-model="form.identityCard"
            placeholder="请输入18位身份证号"
            maxlength="18"
          />
        </el-form-item>

        <!-- <el-form-item label="推荐人ID" prop="fatherId">
          <el-input
            v-model="form.fatherId"
            placeholder="请输入推荐人分销员ID（可选）"
            type="number"
            min="0"
          />
        </el-form-item> -->

        <el-form-item label="推荐人" prop="distributorCode">
          <div style="display: flex; gap: 10px">
            <el-input
              v-model="distributorCode"
              placeholder="请输入推荐人分销员编号（可选）"
              @blur="searchDistributorByCode"
              clearable
            />
            <el-button
              type="primary"
              @click="searchDistributorByCode"
              :loading="searching"
            >
              查询
            </el-button>
          </div>
          <div
            v-if="recommendDistributorName"
            style="margin-top: 5px; color: #67c23a"
          >
            推荐人：{{ recommendDistributorName }}（ID: {{ form.fatherId }}）
          </div>
          <div
            v-else-if="distributorCode"
            style="margin-top: 5px; color: #e6a23c"
          >
            请输入有效的分销员编号
          </div>
        </el-form-item>

        <el-form-item label="备注信息" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入申请备注（可选）"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <!-- 新增：分销协议展示区域 -->
      <el-alert type="info" :closable="false" style="margin-bottom: 15px">
        <div style="display: flex; align-items: center">
          <el-checkbox
            v-model="form.agreement"
            style="margin-right: 10px"
          ></el-checkbox>
          <span>我已阅读并同意</span>
          <el-button
            type="text"
            @click="showProtocolDialog = true"
            style="padding: 0; margin: 0 5px"
            >《分销协议》</el-button
          >
          <span>的所有条款</span>
        </div>
      </el-alert>

      <!-- 新增：协议弹窗 -->
      <el-dialog title="分销协议" v-model="showProtocolDialog" width="600px">
        <div
          v-if="protocolContent"
          class="protocol-content"
          v-html="protocolContent"
        ></div>
        <div v-else class="loading-text">协议内容加载中...</div>
        <template #footer>
          <div style="text-align: right">
            <el-button @click="showProtocolDialog = false">关闭</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 新增：协议确认对话框 -->
      <el-dialog
        title="请阅读并同意以下条款"
        v-model="showAgreementDialog"
        width="400px"
      >
        <p>请阅读并同意以下条款：</p>
        <p style="text-align: center; margin: 20px 0">
          <el-button type="text" @click="showProtocolDialog = true"
            >《分销协议》</el-button
          >
        </p>
        <template #footer>
          <div class="dialog-footer" style="text-align: center">
            <el-button @click="showAgreementDialog = false">不同意</el-button>
            <el-button type="primary" @click="handleAgreeProtocol"
              >同意</el-button
            >
          </div>
        </template>
      </el-dialog>

      <template #footer>
        <div class="dialog-footer" style="text-align: center; margin-top: 20px">
          <el-button type="primary" @click="submitForm" size="medium"
            >提交申请</el-button
          >
          <el-button @click="resetForm" size="medium">重置表单</el-button>
        </div>
      </template>
    </el-card>

    <!-- 认证成功后的附加信息 -->
    <el-card v-if="authStatus === '1'">
      <div class="title">您的分销员信息</div>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="分销员编号">{{
          distributorInfo.distributorCode || "--"
        }}</el-descriptions-item>
        <el-descriptions-item label="当前等级">{{
          distributorInfo.gradeName || "--"
        }}</el-descriptions-item>
        <el-descriptions-item label="团队人数"
          >{{ distributorInfo.teamCount || 0 }}人</el-descriptions-item
        >
        <el-descriptions-item label="加入时间">{{
          distributorInfo.bindTime || "--"
        }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 上级绑定对话框 -->
    <el-dialog
      title="上级绑定"
      v-model="bindSuperiorDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="bindSuperiorFormRef"
        :model="bindSuperiorForm"
        :rules="bindSuperiorRules"
        label-width="120px"
      >
        <el-form-item label="分销员编号" prop="distributorCode">
          <el-input
            v-model="bindSuperiorForm.distributorCode"
            placeholder="请输入分销员编号"
            clearable
            @blur="searchDistributorForBind"
          />
        </el-form-item>

        <el-form-item label="分销员信息" v-if="targetDistributorInfo.realName">
          <div
            style="
              color: #67c23a;
              padding: 8px;
              background: #f0f9ff;
              border-radius: 4px;
            "
          >
            {{ targetDistributorInfo.realName }}
            (ID: {{ targetDistributorInfo.distributorId }})
          </div>
        </el-form-item>

        <el-form-item label="上级编号" prop="superiorDistributorCode">
          <el-input
            v-model="bindSuperiorForm.superiorDistributorCode"
            placeholder="请输入上级分销员编号"
            clearable
            @blur="searchSuperiorDistributor"
          />
        </el-form-item>

        <el-form-item label="上级信息" v-if="superiorDistributorInfo.realName">
          <div
            style="
              color: #67c23a;
              padding: 8px;
              background: #f0f9ff;
              border-radius: 4px;
            "
          >
            {{ superiorDistributorInfo.realName }}
            (ID: {{ superiorDistributorInfo.distributorId }})
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="bindSuperiorDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleBindSuperior"
            :loading="bindLoading"
            :disabled="
              !targetDistributorInfo.distributorId ||
              !superiorDistributorInfo.distributorId
            "
          >
            确认绑定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

  
<script>
import {
  getCurrentDistributor,
  applyDistributor,
  applicationDistributor,
  selectDistributorWhereUserId,
  getDistributionProtocol,
  getDistributorByCode,
  bindSuperiorDistributor,
} from "@/api/ruoyi/distributor";

// import {
//   getDistributionProtocol,
// } from "@/api/ruoyi/distributionConfig";

import { getToken } from "@/utils/auth";

export default {
  name: "DistributorAuth",
  data() {
    // 身份证验证规则
    const validateIDCard = (rule, value, callback) => {
      if (!value) {
        callback(new Error("身份证号不能为空"));
      } else if (
        !/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/.test(
          value
        )
      ) {
        callback(new Error("请输入有效的身份证号码"));
      } else {
        callback();
      }
    };

    // 手机号验证规则
    const validateMobile = (rule, value, callback) => {
      if (!value) {
        callback(new Error("手机号不能为空"));
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    };

    // 协议同意验证规则
    const validateAgreement = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请阅读并同意分销协议"));
      } else {
        callback();
      }
    };

    return {
      // 新增：分销员编号和推荐人姓名
      distributorCode: "",
      recommendDistributorName: "",

      // 上级绑定相关数据
      bindSuperiorDialogVisible: false,
      bindLoading: false,
      bindSuperiorForm: {
        distributorCode: "",
        superiorDistributorCode: "",
      },
      targetDistributorInfo: {},
      superiorDistributorInfo: {},

      // 上级绑定表单验证规则
      bindSuperiorRules: {
        distributorCode: [
          { required: true, message: "分销员编号不能为空", trigger: "blur" },
        ],
        superiorDistributorCode: [
          {
            required: true,
            message: "上级分销员编号不能为空",
            trigger: "blur",
          },
        ],
      },

      // 认证状态: null未申请, 0审核中, 1已通过, 2未通过
      authStatus: null,
      // 分销员详细信息
      distributorInfo: {},
      // 协议内容和状态
      protocolContent: "",
      showProtocolDialog: false,
      // 新增：协议确认对话框显示状态
      showAgreementDialog: false,
      // 表单数据
      form: {
        realName: null,
        mobile: null,
        identityCard: null,
        fatherId: null,
        remark: null,
        agreement: false,
      },
      // 验证规则
      rules: {
        realName: [
          { required: true, message: "真实姓名不能为空", trigger: "blur" },
          { min: 2, max: 20, message: "姓名长度为2-20个字符", trigger: "blur" },
          {
            pattern: /^[\u4e00-\u9fa5]+$/,
            message: "请输入中文姓名",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, validator: validateMobile, trigger: "blur" },
        ],
        identityCard: [
          { required: true, validator: validateIDCard, trigger: "blur" },
        ],
        // fatherId: [
        //   {
        //     pattern: /^\d{1,11}$/,
        //     message: "请输入有效的推荐人ID",
        //     trigger: "blur",
        //   },
        // ],
        agreement: [{ validator: validateAgreement, trigger: "change" }],
      },
    };
  },
  async created() {
    // 修复点3：使用双重检查机制（参考商家认证页面）
    this.checkDistributorStatus();
    // 新增：获取分销协议内容
    try {
      const res = await getDistributionProtocol();
      if (res.code === 200) {
        this.protocolContent = res.data;
      } else {
        console.error("获取分销协议失败:", res.msg);
      }
    } catch (error) {
      console.error("获取分销协议异常:", error);
    }
  },
  methods: {
    // 显示上级绑定对话框
    showBindSuperiorDialog() {
      this.bindSuperiorDialogVisible = true;
      this.resetBindForm();

      // 自动填入当前登录用户的分销员编号
      if (this.distributorInfo && this.distributorInfo.distributorCode) {
        this.bindSuperiorForm.distributorCode =
          this.distributorInfo.distributorCode;
        // 自动查询分销员信息
        this.searchDistributorForBind();
      }
    },

    // 重置绑定表单
    resetBindForm() {
      this.bindSuperiorForm = {
        distributorCode: "",
        superiorDistributorCode: "",
      };
      this.targetDistributorInfo = {};
      this.superiorDistributorInfo = {};
      this.$nextTick(() => {
        if (this.$refs.bindSuperiorFormRef) {
          this.$refs.bindSuperiorFormRef.clearValidate();
        }
      });
    },

    // 查询要绑定的分销员信息
    async searchDistributorForBind() {
      if (!this.bindSuperiorForm.distributorCode) {
        this.targetDistributorInfo = {};
        return;
      }

      try {
        const res = await getDistributorByCode(
          this.bindSuperiorForm.distributorCode
        );
        if (res.code === 200 && res.data) {
          this.targetDistributorInfo = res.data;
          this.$modal.msgSuccess(`找到分销员：${res.data.realName}`);
        } else {
          this.targetDistributorInfo = {};
          this.$modal.msgError(res.msg || "分销员编号不存在");
        }
      } catch (error) {
        console.error("查询分销员失败:", error);
        this.targetDistributorInfo = {};
        this.$modal.msgError("查询失败，请重试");
      }
    },

    // 查询上级分销员信息
    async searchSuperiorDistributor() {
      if (!this.bindSuperiorForm.superiorDistributorCode) {
        this.superiorDistributorInfo = {};
        return;
      }

      try {
        const res = await getDistributorByCode(
          this.bindSuperiorForm.superiorDistributorCode
        );
        if (res.code === 200 && res.data) {
          this.superiorDistributorInfo = res.data;
          this.$modal.msgSuccess(`找到上级分销员：${res.data.realName}`);
        } else {
          this.superiorDistributorInfo = {};
          this.$modal.msgError(res.msg || "上级分销员编号不存在");
        }
      } catch (error) {
        console.error("查询上级分销员失败:", error);
        this.superiorDistributorInfo = {};
        this.$modal.msgError("查询失败，请重试");
      }
    },

    // 处理上级绑定
    async handleBindSuperior() {
      try {
        // 表单验证
        await this.$refs.bindSuperiorFormRef.validate();

        // 检查分销员信息是否存在
        if (!this.targetDistributorInfo.distributorId) {
          this.$modal.msgError("请先查询并确认分销员信息");
          return;
        }

        if (!this.superiorDistributorInfo.distributorId) {
          this.$modal.msgError("请先查询并确认上级分销员信息");
          return;
        }

        // 检查是否绑定自己
        if (
          this.targetDistributorInfo.distributorId ===
          this.superiorDistributorInfo.distributorId
        ) {
          this.$modal.msgError("不能将自己绑定为自己的上级");
          return;
        }

        this.bindLoading = true;

        // 准备绑定数据 - 修改为符合后端接口要求的参数名
        const bindData = {
          superiorDistributorCode:
            this.bindSuperiorForm.superiorDistributorCode,
          remark: "管理员手动绑定上级关系",
        };

        // 调用绑定接口
        const res = await bindSuperiorDistributor(bindData);

        if (res.code === 200) {
          this.$modal.msgSuccess("上级绑定成功");
          this.bindSuperiorDialogVisible = false;
          this.resetBindForm();

          // 可以根据需要刷新页面数据
          // await this.loadDistributorList();
        } else {
          this.$modal.msgError(res.msg || "上级绑定失败");
        }
      } catch (error) {
        console.error("上级绑定失败:", error);
        if (error instanceof Error) {
          // 如果是验证错误，不显示错误提示
          return;
        }
        this.$modal.msgError("绑定失败，请重试");
      } finally {
        this.bindLoading = false;
      }
    },

    // 新增：根据分销员编号查询分销员
    async searchDistributorByCode() {
      if (!this.distributorCode) {
        this.recommendDistributorName = "";
        this.form.fatherId = null;
        return;
      }

      try {
        // 使用新的getDistributorByCode接口
        const res = await getDistributorByCode(this.distributorCode);

        if (res.code === 200 && res.data) {
          const distributor = res.data;
          this.recommendDistributorName = distributor.realName;
          this.form.fatherId = distributor.distributorId;

          console.log("找到推荐人：", distributor.distributorId);

          this.$modal.msgSuccess(`找到推荐人：${distributor.realName}`);
        } else {
          this.recommendDistributorName = "";
          this.form.fatherId = null;
          this.$modal.msgError(res.msg || "分销员编号不存在");
        }
      } catch (error) {
        console.error("查询分销员失败:", error);
        this.$modal.msgError("查询失败，请重试");
      }
    },

    // 修复点4：重构状态获取逻辑（完全参考商家认证页面）
    async checkDistributorStatus() {
      try {
        // 先检查是否存在记录
        const existsRes = await selectDistributorWhereUserId();

        if (!existsRes.data) {
          this.authStatus = null; // 无记录
        } else {
          // 存在记录时获取详细状态
          const statusRes = await getCurrentDistributor();
          if (statusRes.code === 200 && statusRes.data) {
            this.authStatus = statusRes.data.authStatus;
            this.distributorInfo = statusRes.data;
          } else {
            this.authStatus = null;
          }
        }
      } catch (error) {
        console.error("认证状态检查失败:", error);
        this.authStatus = null;
      }
    },

    // 新增：处理同意协议
    handleAgreeProtocol() {
      this.form.agreement = true;
      this.showAgreementDialog = false;
      this.submitForm(); // 重新提交
    },

    // 提交表单
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          // 新增：检查用户是否同意协议
          if (!this.form.agreement) {
            this.showAgreementDialog = true;
            // this.$modal.msgError("请阅读并同意分销协议");
            return; // 阻止提交
          }

          // 新增：检查推荐人分销员编号是否有效
          if (this.distributorCode && !this.form.fatherId) {
            this.$modal.msgError("推荐人分销员编号无效，请重新输入");
            return;
          }

          // 处理推荐人ID
          if (this.form.fatherId === "" || this.form.fatherId === null) {
            this.form.fatherId = 0;
          }

          try {
            const res = await applicationDistributor(this.form);
            if (res.code === 200) {
              this.$modal.msgSuccess("申请提交成功，请等待审核");
              await this.checkDistributorStatus();
            } else {
              this.$modal.msgError(res.msg || "申请提交失败");
            }
          } catch (error) {
            console.error("提交申请失败:", error);
            this.$modal.msgError("请求异常，请稍后重试");
          }
        }
      });
    },

    // 重置表单
    resetForm() {
      this.$refs.form.resetFields();
      this.form.fatherId = null; // 特殊处理数字类型字段
      // 新增：重置分销员编号和推荐人姓名
      this.distributorCode = "";
      this.recommendDistributorName = "";
    },

    // 格式化手机号码显示
    formatPhone(value) {
      return value.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
    },
  },
  computed: {
    // 状态标题
    statusTitle() {
      switch (this.authStatus) {
        case "0":
          return "认证审核中";
        case "1":
          return "认证已通过";
        case "2":
          return "认证未通过";
        default:
          return "未提交认证信息";
      }
    },
    // 状态类型
    statusType() {
      switch (this.authStatus) {
        case "0":
          return "warning";
        case "1":
          return "success";
        case "2":
          return "danger";
        default:
          return "info";
      }
    },
    // 状态描述
    statusText() {
      switch (this.authStatus) {
        case "0":
          return "您的分销员认证申请已提交，请耐心等待审核";
        case "1":
          return "恭喜！您已成为认证分销员，可以开始分销商品";
        case "2":
          return "您的申请未通过审核，请检查信息后重新提交";
        default:
          return "您尚未申请成为分销员，填写以下信息开始申请";
      }
    },
  },
};
</script>
  
<style scoped>
.title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  text-align: center;
  color: #333;
}

.distributor-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.distributor-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.dialog-footer {
  padding: 15px 0 10px;
}

::v-deep .el-descriptions__label {
  width: 120px;
  font-weight: 600;
}
</style>